/**
 * 事件分发方法，可以在组件中使用，也可以在页面中使用，方便页面间数据通信，特别是页面数据的状态同步。
 * 
 * @param {String} name 事件名称，即页面中注册的用于调用的方法名
 * @param {any} props 事件数据，事件发送时传递的数据，可以是String，Number，Boolean，Object等，视具体事件处理逻辑而定，没有固定格式
 * @param {Boolean} isAll 事件传递方式，是否全部页面分发，默认分发给所有页面
 */
const emitEvent = function (name, props, isAll = true) {
  let pages = getCurrentPages()
  if (isAll) {
    for (let i = 0, len = pages.length; i < len; i++) {
      let page = pages[i]
      if (page.hasOwnProperty(name) && typeof (page[name]) === 'function') page[name](props)
    }
  } else {
    if (pages.length > 1) {
      let lastPage = pages[pages.length - 2]
      if (lastPage.hasOwnProperty(name) && typeof (lastPage[name]) === 'function') lastPage[name](props)
    }
  }
}

// px转rpx
const pxToRpx = function (px) {
  return wx.$pro.getSystemInfo().then(systemInfo => 750 / systemInfo.windowWidth * px)
}

// rpx转px
const rpxToPx = function (rpx) {
  return wx.$pro.getSystemInfo().then(systemInfo => 750 / systemInfo.windowWidth / 750 * rpx)
}

// 计算scrollview能够使用的剩余高度
const getScrollViewSize = function (deductedSize) {
  return wx.$pro.getSystemInfo()
    .then(res => this.getPxToRpx(res.windowHeight))
    .then(res => res - deductedSize)
}

// 对象转query
const stringifyQuery = function (query) {
  return Object.keys(query)
    .map(key => `${key}=${query[key]}`)
    .join('&')
}
// query转对象
const queryToObject = function (query) {
  let _query = {}
  query.split('&').forEach(item => {
    const arr = item.split('=')
    _query[arr[0]] = arr[1]
  })
  return _query
}
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const formatTimeTwo = function (number, format) {
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));
  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));
  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}

const getAges = function (strBirthday) {
  var returnAge = '';
  var mouthAge = '';
  var strBirthdayArr = strBirthday
  var birthYear = strBirthdayArr.substring(0,4);
  var birthMonth = strBirthdayArr.substring(4, 6);
  var birthDay = strBirthdayArr.substring(6, 8);
  var d = new Date();
  var nowYear = d.getFullYear();
  var nowMonth = d.getMonth() + 1;
  var nowDay = d.getDate();
  if (nowYear == birthYear) {
    returnAge = 0; //同年 则为0岁
    var monthDiff = nowMonth - birthMonth; //月之差 
    if (monthDiff < 0) {
    } else {
      mouthAge = monthDiff + '个月';
    }
  } else {
    var ageDiff = nowYear - birthYear; //年之差
    if (ageDiff > 0) {
      if (nowMonth == birthMonth) {
        var dayDiff = nowDay - birthDay; //日之差 
        if (dayDiff < 0) {
          returnAge = ageDiff - 1
        } else {
          returnAge = ageDiff
        }
      } else {
        var monthDiff = nowMonth - birthMonth; //月之差 
        if (monthDiff < 0) {
          returnAge = ageDiff - 1
        } else {
          mouthAge = monthDiff + '个月';
          returnAge = ageDiff
        }
      }
    } else {
      returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
    }
  }
  // return returnAge + mouthAge; //返回周岁年龄+月份
  return returnAge
}

const uuid = function () {
  var s = []
  var hexDigits = "0123456789abcdef"
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substring(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = "4"
  s[19] = hexDigits.substring((s[19] & 0x3) | 0x8, 1)
  s[8] = s[13] = s[18] = s[23] = "-"
  var uuid = s.join("")
  return uuid
}

const filterMobile = function (mobile) {
  let mobileReg = /^1[0-9]\d{9}$/
  let valid = true
  if (!mobile || !mobileReg.test(mobile)) valid = false
  return valid
}
const specialPlane = function (mobile) {
  let mobileReg = /^\d{3,4}\d{7,8}$/
  let valid = true
  if (!mobile || !mobileReg.test(mobile)) valid = false
  return valid
}

const filterEmail = function (email) {
  let emailReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
  let valid = true
  if (!email || !emailReg.test(email)) valid = false
  return valid
}

const filterMobileOrEmail = function (str) {
  let mobileReg = /^1[0-9]\d{9}$/
  let email = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
  let valid = true
  if (str.indexOf('/') === -1) {
    valid = false
  } else {
    let strArr = str.split('/')
    if (!mobileReg.test(strArr[0]) || !email.test(strArr[1])) valid = false
  }
  return valid
}

const customId = (randomLength) => {
  return Number(Math.random().toString().substr(3, randomLength) + Date.now()).toString(36)
}

export {
  emitEvent,
  pxToRpx,
  rpxToPx,
  getScrollViewSize,
  stringifyQuery,
  queryToObject,
  formatTimeTwo,
  getAges,
  uuid,
  filterMobile,
  filterEmail,
  filterMobileOrEmail,
  specialPlane,
  customId
}
